package com.kczd.jinlan.view.mine;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kczd.jinlan.R;
import com.kczd.jinlan.utils.AlertIosDialog;
import com.kczd.jinlan.utils.Config;
import com.kczd.jinlan.utils.PhotoUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * yang_g
 * 编辑资料
 * Created by Administrator on 2017/5/15.
 */

public class EditDataActivity extends Activity implements View.OnClickListener {
    private static final String TAG="EditDataActivity.class";
    private RelativeLayout linear_edit_name;//编辑昵称
    private RelativeLayout Linear_autograph;//签名
    private TextView id_fanhui;//返回
    private TextView commitmine;//提交
    private TextView mNickname;//用户名
    private TextView sife_sign;//签名

    private ImageView mImageView;//头像
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int NICKNAME = 3;
    private static final int SIGNTEXT = 4;
    protected static Uri tempUri;
    String imagePath="";
    String url = Config.net_addr + "user/info";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editdata_activity);
        setUserInfo();
    }
    public void setUserInfo() {
        String uImage =Config.user.getHead_pic();
        Log.e("tag", "uimage---->>>" + uImage);
        // 显示图片的配置
        DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.img_loading)
                .showImageOnFail(R.mipmap.img_fail).cacheInMemory(true).cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
        ImageLoader.getInstance().displayImage(uImage, mImageView, options);
        mNickname.setText(Config.user.getNickname());
        sife_sign.setText(Config.user.getSign());
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        linear_edit_name = (RelativeLayout) findViewById(R.id.linear_edit_name);
        linear_edit_name.setOnClickListener(this);
        Linear_autograph = (RelativeLayout) findViewById(R.id.Linear_autograph);
        Linear_autograph.setOnClickListener(this);
        id_fanhui = (TextView) findViewById(R.id.id_fanhui);
        id_fanhui.setOnClickListener(this);

        mImageView = (ImageView) findViewById(R.id.circle_view);
        mImageView.setOnClickListener(this);
        commitmine= (TextView) findViewById(R.id.id_tijiao);
        commitmine.setOnClickListener(this);
        mNickname= (TextView) findViewById(R.id.id_nickname);
        sife_sign= (TextView) findViewById(R.id.sife_sign);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.linear_edit_name://编辑昵称
                Intent intent=new Intent(EditDataActivity.this, NicknameActivity.class);
                startActivityForResult(intent,NICKNAME);
                break;
            case R.id.Linear_autograph://个性签名
                Intent intent1=new Intent(EditDataActivity.this, AutographActivity.class);
                startActivityForResult(intent1,SIGNTEXT);
                break;
            case R.id.id_fanhui://返回
                finish();
                break;
            case R.id.circle_view://头像
                showChoosePicDialog();
                break;
            case R.id.id_tijiao://提交
                if (!subpre()) {
                    new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE).setTitleText("必填验证").setContentText("你是不是忘了填什么")
                            .show();
                    return;
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            commiteMeans();
                        }
                    }).start();
                    break;
                }
        }
    }
    public boolean subpre() {
        String nickname = mNickname.getText().toString();

        if (nickname.isEmpty()) {
            return false;
        }
        return true;
    }

    /**
     * 提交资料
     */
    public  void commiteMeans() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("token", Config.user.getToken())
                .add("nickname", mNickname.getText().toString())
                .add("head_pic", imagePath)
                .add("self_sign", sife_sign.getText().toString())
                .add("act", "edit")
                .add("sex", "0")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            Log.e(TAG,"commiteMeans:"+val);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(Config.code.equals(jsonResult.getString("code"))){
                    JSONObject jb= jsonResult.getJSONObject("data");
                    Config.user.setNickname(jb.getString("nickname"));
                    Config.user.setSign( jb.getString("self_sign"));
                    Config.user.setHead_pic(jb.getString("head_pic"));
                    Config.saveObject(getBaseContext(),Config.user);
                     EditDataActivity.this.finish();
                    Toast.makeText(EditDataActivity.this,"保存成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(EditDataActivity.this,"保存失败",Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    /**
     * 显示修改头像的对话框
     */
    private void showChoosePicDialog() {
        new AlertIosDialog(this).builder(R.style.ActionListDialogStyle).setAlertDialogSize(1).setSelsctPanel(R.mipmap.camera, R.mipmap.picture, "拍照", "从相册中选择")
                .setLeftPanelOnClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 拍照
                        Intent openCameraIntent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        tempUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "image.jpg"));
                        // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                        startActivityForResult(openCameraIntent, TAKE_PICTURE);
                    }
                }).setRightPanelOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 选择本地照片
                Intent openAlbumIntent = new Intent(
                        Intent.ACTION_GET_CONTENT);
                openAlbumIntent.setType("image/*");
                startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
            }
        }).setCanaleBtnClickListener("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case TAKE_PICTURE:
                    startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
                case NICKNAME:
                    mNickname.setText(data.getStringExtra("nickname"));
                    break;
                case SIGNTEXT:
                    sife_sign.setText(data.getStringExtra("signtext"));
                    break;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            photo = PhotoUtils.toRoundBitmap(photo, tempUri); // 这个时候的图片已经被处理成圆形的了
            mImageView.setImageBitmap(photo);
            ByteArrayOutputStream stream=new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG,60,stream);
            byte[] bytes=stream.toByteArray();
            imagePath=new String(Base64.encodeToString(bytes,Base64.DEFAULT));
        }
    }
}
